package com.bangmai.service.impl;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.springframework.stereotype.Component;

import com.alibaba.druid.sql.visitor.functions.Now;
import com.bangmai.model.Receiver;
import com.bangmai.service.AnalysisService;

/**
 * 解析XML文件的实现类
 * 
 * @author dellpc
 *
 */
@Component
public class AnalysisServiceImpl implements AnalysisService {

	@Override
	public List<Receiver> analysisXml(String filePath, String element) throws JDOMException, IOException {
		// TODO Auto-generated method stub
		List<Receiver> receivers = new ArrayList<>();
		File file = new File(filePath);
		File[] files = file.listFiles();
		if (files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				Receiver receiver = new Receiver();
				SAXBuilder builder = new SAXBuilder();
				Document document = builder.build(filePath+"/"+files[i].getName());
				Element root = document.getRootElement();
				List persons = root.getChildren(element);
				if (!persons.isEmpty()) {
					for (int j = 0; j < persons.size(); j++) {
						
						Element person = (Element) persons.get(j);
						List pros = person.getChildren();
						System.out.println(person.getName());
						if (!pros.isEmpty()) {
							for (int m = 0; m < pros.size(); m++) {
								Element element_ = (Element) pros.get(m);
								List<Element> info = element_.getChildren();
								if (element_.getName().equals("Status")) {
									receiver.setCode(element_.getValue());
									if (element_.getValue().equals("10")) {
										receiver.setStatus("1");
									}else  {
										receiver.setStatus("0");
										
									}
									
								}else if (element_.getName().equals("Notes")) {
									receiver.setInfo(element_.getValue());
									
								}
								if (!info.isEmpty()) {
									for (int n = 0; n < info.size(); n++) {
										Element element2 = info.get(n);
										System.out.println(element2.getName() + "->" + element2.getValue());
										if (element2.getName().equals("ReturnCode")) {
											receiver.setCode(element2.getValue());
											if (element2.getValue().equals("C01")) {
												receiver.setStatus("1");
											} else {
												receiver.setStatus("0");
											}
										} else if (element2.getName().equals("ReturnInfo")) {
											receiver.setInfo(element2.getValue());
										}
										
									}

								}

							}
						} else {
							System.out.println(person.getName() + "--" + person.getValue());
						}

					}
				}
				receiver.setDate(new Date());
				receiver.setOrder_id("1111111111111");
				receivers.add(receiver);
				document=null;
				builder=null;
				file=null;

			}

		}
		return receivers;
	}

}
